<template>
  <div class="min-h-screen p-6" style="background-color: #FAF9F5;">
    <!-- 页面头部 -->
    <div class="mb-6">
      <div class="flex items-center justify-between">
        <div>
          <h1 class="text-2xl font-bold text-gray-900">班级管理</h1>
          <p class="mt-1 text-sm text-gray-600">管理班级信息，维护班级与专业的关联关系，分配学生到班级</p>
        </div>
        <button
          @click="showAddModal = true"
          class="inline-flex items-center px-4 py-2 text-white text-sm font-medium rounded-[0.6rem] border border-gray-300 hover:border-gray-400 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-all duration-200 active:scale-[0.985]"
          style="background-color: #3B82F6; box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);"
        >
          <PlusIcon class="w-4 h-4 mr-2" />
          添加班级
        </button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="rounded-lg border border-gray-200 p-6 mb-6" style="background-color: #FAF9F5; box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);">
      <div class="grid grid-cols-1 md:grid-cols-5 gap-4">
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">班级名称</label>
          <input
            v-model="searchForm.name"
            type="text"
            placeholder="请输入班级名称"
            class="w-full px-3 py-2 border border-gray-300 rounded-[0.6rem] focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200"
            style="background-color: #F5F5F0; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);"
          />
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">所属专业</label>
          <Listbox v-model="searchForm.major">
            <div class="relative">
              <ListboxButton class="relative w-full cursor-default rounded-[0.6rem] py-2 pl-3 pr-10 text-left border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200" style="background-color: #F5F5F0; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);">
                <span class="block truncate">{{ searchForm.major || '请选择专业' }}</span>
                <span class="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2">
                  <ChevronUpDownIcon class="h-5 w-5 text-gray-400" aria-hidden="true" />
                </span>
              </ListboxButton>
              <transition
                leave-active-class="transition duration-100 ease-in"
                leave-from-class="opacity-100"
                leave-to-class="opacity-0"
              >
                <ListboxOptions class="absolute z-10 mt-1 max-h-60 w-full overflow-auto rounded-md bg-white py-1 text-base shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none">
                  <ListboxOption value="" class="relative cursor-default select-none py-2 pl-10 pr-4 text-gray-900 hover:bg-blue-100">
                    <span class="block truncate font-normal">全部专业</span>
                  </ListboxOption>
                  <ListboxOption
                    v-for="major in majors"
                    :key="major"
                    :value="major"
                    v-slot="{ active, selected }"
                    class="relative cursor-default select-none py-2 pl-10 pr-4"
                    :class="active ? 'bg-blue-100 text-blue-900' : 'text-gray-900'"
                  >
                    <span class="block truncate" :class="selected ? 'font-medium' : 'font-normal'">
                      {{ major }}
                    </span>
                    <span v-if="selected" class="absolute inset-y-0 left-0 flex items-center pl-3 text-blue-600">
                      <CheckIcon class="h-5 w-5" aria-hidden="true" />
                    </span>
                  </ListboxOption>
                </ListboxOptions>
              </transition>
            </div>
          </Listbox>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">年级</label>
          <select
            v-model="searchForm.grade"
            class="w-full px-3 py-2 border border-gray-300 rounded-[0.6rem] focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200"
            style="background-color: #F5F5F0; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);"
          >
            <option value="">全部年级</option>
            <option value="2024">2024级</option>
            <option value="2023">2023级</option>
            <option value="2022">2022级</option>
            <option value="2021">2021级</option>
          </select>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">班主任</label>
          <input
            v-model="searchForm.teacher"
            type="text"
            placeholder="请输入班主任姓名"
            class="w-full px-3 py-2 border border-gray-300 rounded-[0.6rem] focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200"
            style="background-color: #F5F5F0; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);"
          />
        </div>
        <div class="flex items-end gap-2">
          <button
            @click="handleSearch"
            class="flex-1 px-4 py-2 text-white text-sm font-medium rounded-[0.6rem] border border-gray-300 hover:border-gray-400 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-all duration-200 active:scale-[0.985]"
            style="background-color: #3B82F6; box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);"
          >
            <MagnifyingGlassIcon class="w-4 h-4 mr-2 inline" />
            搜索
          </button>
          <button
            @click="handleReset"
            class="px-4 py-2 text-gray-700 text-sm font-medium rounded-[0.6rem] border border-gray-300 hover:border-gray-400 hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 transition-all duration-200 active:scale-[0.985]"
            style="background-color: #F5F5F0; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);"
          >
            重置
          </button>
        </div>
      </div>
    </div>

    <!-- 班级列表 -->
    <div class="rounded-lg border border-gray-200" style="background-color: #FAF9F5; box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);">
      <div class="px-6 py-4 border-b border-gray-200">
        <div class="flex items-center justify-between">
          <h2 class="text-lg font-medium text-gray-900">班级列表</h2>
          <div class="flex items-center gap-4">
            <span class="text-sm text-gray-500">共 {{ filteredClasses.length }} 个班级</span>
            <div class="flex items-center gap-2">
              <button
                @click="handleBatchDelete"
                :disabled="selectedClasses.length === 0"
                class="px-3 py-1.5 text-sm font-medium text-red-600 rounded-[0.6rem] border border-red-200 hover:border-red-300 hover:bg-red-100 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200 active:scale-[0.985]"
                style="background-color: #FEF2F2; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);"
              >
                <TrashIcon class="w-4 h-4 mr-1 inline" />
                批量删除
              </button>
              <button
                @click="handleExport"
                class="px-3 py-1.5 text-sm font-medium text-green-600 rounded-[0.6rem] border border-green-200 hover:border-green-300 hover:bg-green-100 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 transition-all duration-200 active:scale-[0.985]"
                style="background-color: #F0FDF4; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);"
              >
                <ArrowDownTrayIcon class="w-4 h-4 mr-1 inline" />
                导出
              </button>
            </div>
          </div>
        </div>
      </div>

      <div class="overflow-x-auto">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
            <tr>
              <th class="px-6 py-3 text-left">
                <input
                  type="checkbox"
                  :checked="selectedClasses.length === filteredClasses.length && filteredClasses.length > 0"
                  @change="handleSelectAll"
                  class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                />
              </th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">班级名称</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">所属专业</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">年级</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">班主任</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">学生人数</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">容量</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <tr v-for="classItem in paginatedClasses" :key="classItem.id" class="hover:bg-gray-50">
              <td class="px-6 py-4">
                <input
                  type="checkbox"
                  :value="classItem.id"
                  v-model="selectedClasses"
                  class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                />
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="flex items-center">
                  <div>
                    <div class="text-sm font-medium text-gray-900">{{ classItem.name }}</div>
                    <div class="text-sm text-gray-500">{{ classItem.code }}</div>
                  </div>
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ classItem.major }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ classItem.grade }}级</td>
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="flex items-center">
                  <div>
                    <div class="text-sm font-medium text-gray-900">{{ classItem.teacher }}</div>
                    <div class="text-sm text-gray-500">{{ classItem.teacherPhone }}</div>
                  </div>
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                <div class="flex items-center">
                  <span class="text-lg font-semibold text-blue-600">{{ classItem.studentCount }}</span>
                  <span class="text-gray-400 ml-1">人</span>
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ classItem.capacity }}人</td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span
                  :class="{
                    'bg-green-100 text-green-800': classItem.status === '正常',
                    'bg-red-100 text-red-800': classItem.status === '停用',
                    'bg-yellow-100 text-yellow-800': classItem.status === '满员'
                  }"
                  class="inline-flex px-2 py-1 text-xs font-semibold rounded-full"
                >
                  {{ classItem.status }}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                <div class="flex items-center gap-2">
                  <button
                    @click="handleManageStudents(classItem)"
                    class="text-purple-600 hover:text-purple-900 transition-colors"
                    title="管理学生"
                  >
                    <UsersIcon class="w-4 h-4" />
                  </button>
                  <button
                    @click="handleEdit(classItem)"
                    class="text-blue-600 hover:text-blue-900 transition-colors"
                    title="编辑"
                  >
                    <PencilIcon class="w-4 h-4" />
                  </button>
                  <button
                    @click="handleView(classItem)"
                    class="text-green-600 hover:text-green-900 transition-colors"
                    title="查看详情"
                  >
                    <EyeIcon class="w-4 h-4" />
                  </button>
                  <button
                    @click="handleDelete(classItem)"
                    class="text-red-600 hover:text-red-900 transition-colors"
                    title="删除"
                  >
                    <TrashIcon class="w-4 h-4" />
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- 分页 -->
      <div class="px-6 py-4 border-t border-gray-200">
        <div class="flex items-center justify-between">
          <div class="text-sm text-gray-500">
            显示第 {{ (currentPage - 1) * pageSize + 1 }} - {{ Math.min(currentPage * pageSize, filteredClasses.length) }} 条，共 {{ filteredClasses.length }} 条
          </div>
          <div class="flex items-center gap-2">
            <button
              @click="currentPage--"
              :disabled="currentPage === 1"
              class="px-3 py-1 text-sm font-medium text-gray-500 border border-gray-300 rounded-[0.6rem] hover:border-gray-400 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200 active:scale-[0.985]"
              style="background-color: #F5F5F0; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);"
            >
              上一页
            </button>
            <span class="px-3 py-1 text-sm font-medium text-gray-700">
              {{ currentPage }} / {{ totalPages }}
            </span>
            <button
              @click="currentPage++"
              :disabled="currentPage === totalPages"
              class="px-3 py-1 text-sm font-medium text-gray-500 border border-gray-300 rounded-[0.6rem] hover:border-gray-400 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200 active:scale-[0.985]"
              style="background-color: #F5F5F0; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);"
            >
              下一页
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加/编辑班级弹窗 -->
    <Dialog :open="showAddModal || showEditModal" @close="closeModal" class="relative z-50">
      <div class="fixed inset-0 bg-black/30" aria-hidden="true" />
      <div class="fixed inset-0 flex items-center justify-center p-4">
        <DialogPanel class="w-full max-w-2xl rounded-lg p-6 shadow-xl border border-gray-200" style="background-color: #FAF9F5;">
          <DialogTitle class="text-lg font-medium text-gray-900 mb-4">
            {{ showAddModal ? '添加班级' : '编辑班级' }}
          </DialogTitle>
          
          <form @submit.prevent="handleSubmit" class="space-y-4">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">班级代码 *</label>
                <input
                  v-model="formData.code"
                  type="text"
                  required
                  placeholder="请输入班级代码"
                  class="w-full px-3 py-2 border border-gray-300 rounded-[0.6rem] focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200"
                  style="background-color: #F5F5F0; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);"
                  :class="{ 'border-red-300': errors.code }"
                />
                <p v-if="errors.code" class="mt-1 text-sm text-red-600">{{ errors.code }}</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">班级名称 *</label>
                <input
                  v-model="formData.name"
                  type="text"
                  required
                  placeholder="请输入班级名称"
                  class="w-full px-3 py-2 border border-gray-300 rounded-[0.6rem] focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200"
                  style="background-color: #F5F5F0; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);"
                  :class="{ 'border-red-300': errors.name }"
                />
                <p v-if="errors.name" class="mt-1 text-sm text-red-600">{{ errors.name }}</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">所属专业 *</label>
                <Listbox v-model="formData.major">
                  <div class="relative">
                    <ListboxButton class="relative w-full cursor-default rounded-[0.6rem] py-2 pl-3 pr-10 text-left border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200" style="background-color: #F5F5F0; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);">
                      <span class="block truncate">{{ formData.major || '请选择专业' }}</span>
                      <span class="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2">
                        <ChevronUpDownIcon class="h-5 w-5 text-gray-400" aria-hidden="true" />
                      </span>
                    </ListboxButton>
                    <transition
                      leave-active-class="transition duration-100 ease-in"
                      leave-from-class="opacity-100"
                      leave-to-class="opacity-0"
                    >
                      <ListboxOptions class="absolute z-10 mt-1 max-h-60 w-full overflow-auto rounded-md bg-white py-1 text-base shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none">
                        <ListboxOption
                          v-for="major in majors"
                          :key="major"
                          :value="major"
                          v-slot="{ active, selected }"
                          class="relative cursor-default select-none py-2 pl-10 pr-4"
                          :class="active ? 'bg-blue-100 text-blue-900' : 'text-gray-900'"
                        >
                          <span class="block truncate" :class="selected ? 'font-medium' : 'font-normal'">
                            {{ major }}
                          </span>
                          <span v-if="selected" class="absolute inset-y-0 left-0 flex items-center pl-3 text-blue-600">
                            <CheckIcon class="h-5 w-5" aria-hidden="true" />
                          </span>
                        </ListboxOption>
                      </ListboxOptions>
                    </transition>
                  </div>
                </Listbox>
                <p v-if="errors.major" class="mt-1 text-sm text-red-600">{{ errors.major }}</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">年级 *</label>
                <select
                  v-model="formData.grade"
                  required
                  class="w-full px-3 py-2 border border-gray-300 rounded-[0.6rem] focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200"
                  style="background-color: #F5F5F0; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);"
                >
                  <option value="">请选择年级</option>
                  <option value="2024">2024级</option>
                  <option value="2023">2023级</option>
                  <option value="2022">2022级</option>
                  <option value="2021">2021级</option>
                </select>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">班主任姓名 *</label>
                <input
                  v-model="formData.teacher"
                  type="text"
                  required
                  placeholder="请输入班主任姓名"
                  class="w-full px-3 py-2 border border-gray-300 rounded-[0.6rem] focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200"
                  style="background-color: #F5F5F0; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);"
                />
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">班主任电话</label>
                <input
                  v-model="formData.teacherPhone"
                  type="tel"
                  placeholder="请输入班主任电话"
                  class="w-full px-3 py-2 border border-gray-300 rounded-[0.6rem] focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200"
                  style="background-color: #F5F5F0; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);"
                />
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">班级容量 *</label>
                <input
                  v-model.number="formData.capacity"
                  type="number"
                  required
                  min="1"
                  max="100"
                  placeholder="请输入班级容量"
                  class="w-full px-3 py-2 border border-gray-300 rounded-[0.6rem] focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200"
                  style="background-color: #F5F5F0; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);"
                />
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">状态</label>
                <select
                  v-model="formData.status"
                  class="w-full px-3 py-2 border border-gray-300 rounded-[0.6rem] focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200"
                  style="background-color: #F5F5F0; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);"
                >
                  <option value="正常">正常</option>
                  <option value="停用">停用</option>
                  <option value="满员">满员</option>
                </select>
              </div>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">班级描述</label>
              <textarea
                v-model="formData.description"
                rows="3"
                placeholder="请输入班级描述"
                class="w-full px-3 py-2 border border-gray-300 rounded-[0.6rem] focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200"
                style="background-color: #F5F5F0; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);"
              ></textarea>
            </div>
            
            <div class="flex justify-end gap-3 pt-4">
              <button
                type="button"
                @click="closeModal"
                class="px-4 py-2 text-sm font-medium text-gray-700 rounded-[0.6rem] border border-gray-300 hover:border-gray-400 hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 transition-all duration-200 active:scale-[0.985]"
                style="background-color: #F5F5F0; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);"
              >
                取消
              </button>
              <button
                type="submit"
                :disabled="loading"
                class="px-4 py-2 text-sm font-medium text-white rounded-[0.6rem] border border-gray-300 hover:border-gray-400 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200 active:scale-[0.985]"
                style="background-color: #3B82F6; box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);"
              >
                {{ loading ? '保存中...' : (showAddModal ? '添加' : '保存') }}
              </button>
            </div>
          </form>
        </DialogPanel>
      </div>
    </Dialog>

    <!-- 查看班级详情弹窗 -->
    <Dialog :open="showViewModal" @close="showViewModal = false" class="relative z-50">
      <div class="fixed inset-0 bg-black/30" aria-hidden="true" />
      <div class="fixed inset-0 flex items-center justify-center p-4">
        <DialogPanel class="w-full max-w-2xl rounded-lg bg-white p-6 shadow-xl">
          <DialogTitle class="text-lg font-medium text-gray-900 mb-4">
            班级详情
          </DialogTitle>
          
          <div v-if="viewData" class="space-y-4">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">班级代码</label>
                <p class="text-sm text-gray-900">{{ viewData.code }}</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">班级名称</label>
                <p class="text-sm text-gray-900">{{ viewData.name }}</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">所属专业</label>
                <p class="text-sm text-gray-900">{{ viewData.major }}</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">年级</label>
                <p class="text-sm text-gray-900">{{ viewData.grade }}级</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">班主任</label>
                <p class="text-sm text-gray-900">{{ viewData.teacher }}</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">班主任电话</label>
                <p class="text-sm text-gray-900">{{ viewData.teacherPhone || '未填写' }}</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">学生人数</label>
                <p class="text-sm text-gray-900">{{ viewData.studentCount }}人</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">班级容量</label>
                <p class="text-sm text-gray-900">{{ viewData.capacity }}人</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">状态</label>
                <span
                  :class="{
                    'bg-green-100 text-green-800': viewData.status === '正常',
                    'bg-red-100 text-red-800': viewData.status === '停用',
                    'bg-yellow-100 text-yellow-800': viewData.status === '满员'
                  }"
                  class="inline-flex px-2 py-1 text-xs font-semibold rounded-full"
                >
                  {{ viewData.status }}
                </span>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">创建时间</label>
                <p class="text-sm text-gray-900">{{ viewData.createdAt }}</p>
              </div>
            </div>
            <div v-if="viewData.description">
              <label class="block text-sm font-medium text-gray-700 mb-1">班级描述</label>
              <p class="text-sm text-gray-900">{{ viewData.description }}</p>
            </div>
          </div>
          
          <div class="flex justify-end pt-4">
            <button
              @click="showViewModal = false"
              class="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 transition-colors"
            >
              关闭
            </button>
          </div>
        </DialogPanel>
      </div>
    </Dialog>

    <!-- 学生管理弹窗 -->
    <Dialog :open="showStudentModal" @close="showStudentModal = false" class="relative z-50">
      <div class="fixed inset-0 bg-black/30" aria-hidden="true" />
      <div class="fixed inset-0 flex items-center justify-center p-4">
        <DialogPanel class="w-full max-w-4xl rounded-lg bg-white p-6 shadow-xl">
          <DialogTitle class="text-lg font-medium text-gray-900 mb-4">
            学生管理 - {{ currentClass?.name }}
          </DialogTitle>
          
          <div class="space-y-4">
            <!-- 学生搜索 -->
            <div class="flex items-center gap-4">
              <input
                v-model="studentSearch"
                type="text"
                placeholder="搜索学生姓名或学号"
                class="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
              />
              <button
                @click="showAssignModal = true"
                class="px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-colors"
              >
                分配学生
              </button>
            </div>
            
            <!-- 学生列表 -->
            <div class="border border-gray-200 rounded-lg overflow-hidden">
              <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                  <tr>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">学号</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">姓名</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">性别</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">联系电话</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                  </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                  <tr v-for="student in filteredClassStudents" :key="student.id" class="hover:bg-gray-50">
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{{ student.studentId }}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ student.name }}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ student.gender }}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ student.phone }}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                      <button
                        @click="handleRemoveStudent(student)"
                        class="text-red-600 hover:text-red-900 transition-colors"
                      >
                        移除
                      </button>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
          
          <div class="flex justify-end pt-4">
            <button
              @click="showStudentModal = false"
              class="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 transition-colors"
            >
              关闭
            </button>
          </div>
        </DialogPanel>
      </div>
    </Dialog>

    <!-- 分配学生弹窗 -->
    <Dialog :open="showAssignModal" @close="showAssignModal = false" class="relative z-50">
      <div class="fixed inset-0 bg-black/30" aria-hidden="true" />
      <div class="fixed inset-0 flex items-center justify-center p-4">
        <DialogPanel class="w-full max-w-2xl rounded-lg bg-white p-6 shadow-xl">
          <DialogTitle class="text-lg font-medium text-gray-900 mb-4">
            分配学生到班级
          </DialogTitle>
          
          <div class="space-y-4">
            <input
              v-model="unassignedStudentSearch"
              type="text"
              placeholder="搜索未分配的学生"
              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
            />
            
            <div class="max-h-60 overflow-y-auto border border-gray-200 rounded-lg">
              <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                  <tr>
                    <th class="px-6 py-3 text-left">
                      <input
                        type="checkbox"
                        :checked="selectedStudents.length === filteredUnassignedStudents.length && filteredUnassignedStudents.length > 0"
                        @change="handleSelectAllStudents"
                        class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                      />
                    </th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">学号</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">姓名</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">专业</th>
                  </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                  <tr v-for="student in filteredUnassignedStudents" :key="student.id" class="hover:bg-gray-50">
                    <td class="px-6 py-4">
                      <input
                        type="checkbox"
                        :value="student.id"
                        v-model="selectedStudents"
                        class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                      />
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{{ student.studentId }}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ student.name }}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ student.major }}</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
          
          <div class="flex justify-end gap-3 pt-4">
            <button
              @click="showAssignModal = false"
              class="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 transition-colors"
            >
              取消
            </button>
            <button
              @click="handleAssignStudents"
              :disabled="selectedStudents.length === 0"
              class="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              分配 ({{ selectedStudents.length }})
            </button>
          </div>
        </DialogPanel>
      </div>
    </Dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useAppStore } from '../../stores/app'
import {
  Dialog,
  DialogPanel,
  DialogTitle,
  Listbox,
  ListboxButton,
  ListboxOptions,
  ListboxOption
} from '@headlessui/vue'
import {
  PlusIcon,
  MagnifyingGlassIcon,
  TrashIcon,
  ArrowDownTrayIcon,
  PencilIcon,
  EyeIcon,
  UsersIcon,
  ChevronUpDownIcon,
  CheckIcon
} from '@heroicons/vue/24/outline'

// 使用stores
const appStore = useAppStore()

// 响应式数据
const searchForm = ref({
  name: '',
  major: '',
  grade: '',
  teacher: ''
})

const showAddModal = ref(false)
const showEditModal = ref(false)
const showViewModal = ref(false)
const showStudentModal = ref(false)
const showAssignModal = ref(false)
const loading = ref(false)
const selectedClasses = ref([])
const selectedStudents = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const studentSearch = ref('')
const unassignedStudentSearch = ref('')
const currentClass = ref(null)

const formData = ref({
  code: '',
  name: '',
  major: '',
  grade: '',
  teacher: '',
  teacherPhone: '',
  capacity: 30,
  status: '正常',
  description: ''
})

const errors = ref({})
const viewData = ref(null)

// 模拟数据
const classes = ref([
  {
    id: 1,
    code: 'CS2024-01',
    name: '计算机科学与技术2024-1班',
    major: '计算机科学与技术',
    grade: '2024',
    teacher: '张教授',
    teacherPhone: '13800138001',
    studentCount: 28,
    capacity: 30,
    status: '正常',
    description: '计算机科学与技术专业2024级第一班',
    createdAt: '2024-01-15 10:30:00'
  },
  {
    id: 2,
    code: 'SE2024-01',
    name: '软件工程2024-1班',
    major: '软件工程',
    grade: '2024',
    teacher: '李老师',
    teacherPhone: '13800138002',
    studentCount: 30,
    capacity: 30,
    status: '满员',
    description: '软件工程专业2024级第一班',
    createdAt: '2024-01-15 10:35:00'
  },
  {
    id: 3,
    code: 'EE2024-01',
    name: '电子信息工程2024-1班',
    major: '电子信息工程',
    grade: '2024',
    teacher: '王副教授',
    teacherPhone: '13800138003',
    studentCount: 25,
    capacity: 28,
    status: '正常',
    description: '电子信息工程专业2024级第一班',
    createdAt: '2024-01-15 10:40:00'
  },
  {
    id: 4,
    code: 'ME2023-01',
    name: '机械工程2023-1班',
    major: '机械工程',
    grade: '2023',
    teacher: '刘教授',
    teacherPhone: '13800138004',
    studentCount: 32,
    capacity: 35,
    status: '正常',
    description: '机械工程专业2023级第一班',
    createdAt: '2023-01-15 10:45:00'
  }
])

const majors = ref([
  '计算机科学与技术',
  '软件工程',
  '电子信息工程',
  '机械工程',
  '工商管理',
  '英语'
])

// 模拟学生数据
const students = ref([
  {
    id: 1,
    studentId: '2024001',
    name: '张三',
    gender: '男',
    phone: '13800138001',
    major: '计算机科学与技术',
    classId: 1
  },
  {
    id: 2,
    studentId: '2024002',
    name: '李四',
    gender: '女',
    phone: '13800138002',
    major: '计算机科学与技术',
    classId: 1
  },
  {
    id: 3,
    studentId: '2024003',
    name: '王五',
    gender: '男',
    phone: '13800138003',
    major: '软件工程',
    classId: null
  },
  {
    id: 4,
    studentId: '2024004',
    name: '赵六',
    gender: '女',
    phone: '13800138004',
    major: '软件工程',
    classId: null
  }
])

// 计算属性
const filteredClasses = computed(() => {
  let result = classes.value
  
  if (searchForm.value.name) {
    result = result.filter(classItem => 
      classItem.name.toLowerCase().includes(searchForm.value.name.toLowerCase())
    )
  }
  
  if (searchForm.value.major) {
    result = result.filter(classItem => classItem.major === searchForm.value.major)
  }
  
  if (searchForm.value.grade) {
    result = result.filter(classItem => classItem.grade === searchForm.value.grade)
  }
  
  if (searchForm.value.teacher) {
    result = result.filter(classItem => 
      classItem.teacher.toLowerCase().includes(searchForm.value.teacher.toLowerCase())
    )
  }
  
  return result
})

const totalPages = computed(() => {
  return Math.ceil(filteredClasses.value.length / pageSize.value)
})

const paginatedClasses = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredClasses.value.slice(start, end)
})

const filteredClassStudents = computed(() => {
  if (!currentClass.value) return []
  
  let result = students.value.filter(student => student.classId === currentClass.value.id)
  
  if (studentSearch.value) {
    result = result.filter(student => 
      student.name.toLowerCase().includes(studentSearch.value.toLowerCase()) ||
      student.studentId.toLowerCase().includes(studentSearch.value.toLowerCase())
    )
  }
  
  return result
})

const filteredUnassignedStudents = computed(() => {
  let result = students.value.filter(student => !student.classId)
  
  if (unassignedStudentSearch.value) {
    result = result.filter(student => 
      student.name.toLowerCase().includes(unassignedStudentSearch.value.toLowerCase()) ||
      student.studentId.toLowerCase().includes(unassignedStudentSearch.value.toLowerCase())
    )
  }
  
  return result
})

// 方法
const handleSearch = () => {
  currentPage.value = 1
}

const handleReset = () => {
  searchForm.value = {
    name: '',
    major: '',
    grade: '',
    teacher: ''
  }
  currentPage.value = 1
}

const handleSelectAll = (event) => {
  if (event.target.checked) {
    selectedClasses.value = filteredClasses.value.map(classItem => classItem.id)
  } else {
    selectedClasses.value = []
  }
}

const handleSelectAllStudents = (event) => {
  if (event.target.checked) {
    selectedStudents.value = filteredUnassignedStudents.value.map(student => student.id)
  } else {
    selectedStudents.value = []
  }
}

const handleEdit = (classItem) => {
  formData.value = { ...classItem }
  showEditModal.value = true
}

const handleView = (classItem) => {
  viewData.value = classItem
  showViewModal.value = true
}

const handleManageStudents = (classItem) => {
  currentClass.value = classItem
  studentSearch.value = ''
  showStudentModal.value = true
}

const handleDelete = async (classItem) => {
  if (confirm(`确定要删除班级 "${classItem.name}" 吗？`)) {
    // 模拟删除操作
    const index = classes.value.findIndex(c => c.id === classItem.id)
    if (index > -1) {
      classes.value.splice(index, 1)
    }
    
    // 移除选中状态
    const selectedIndex = selectedClasses.value.indexOf(classItem.id)
    if (selectedIndex > -1) {
      selectedClasses.value.splice(selectedIndex, 1)
    }
    
    // 清除该班级的学生关联
    students.value.forEach(student => {
      if (student.classId === classItem.id) {
        student.classId = null
      }
    })
  }
}

const handleBatchDelete = async () => {
  if (selectedClasses.value.length === 0) return
  
  if (confirm(`确定要删除选中的 ${selectedClasses.value.length} 个班级吗？`)) {
    // 模拟批量删除
    classes.value = classes.value.filter(classItem => !selectedClasses.value.includes(classItem.id))
    
    // 清除这些班级的学生关联
    students.value.forEach(student => {
      if (selectedClasses.value.includes(student.classId)) {
        student.classId = null
      }
    })
    
    selectedClasses.value = []
  }
}

const handleExport = () => {
  // 模拟导出功能
  const csvContent = [
    ['班级代码', '班级名称', '所属专业', '年级', '班主任', '班主任电话', '学生人数', '班级容量', '状态'],
    ...filteredClasses.value.map(classItem => [
      classItem.code,
      classItem.name,
      classItem.major,
      `${classItem.grade}级`,
      classItem.teacher,
      classItem.teacherPhone || '',
      classItem.studentCount,
      classItem.capacity,
      classItem.status
    ])
  ].map(row => row.join(',')).join('\n')
  
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = '班级列表.csv'
  link.click()
}

const handleRemoveStudent = (student) => {
  if (confirm(`确定要将学生 "${student.name}" 从班级中移除吗？`)) {
    const studentIndex = students.value.findIndex(s => s.id === student.id)
    if (studentIndex > -1) {
      students.value[studentIndex].classId = null
    }
    
    // 更新班级学生人数
    const classIndex = classes.value.findIndex(c => c.id === currentClass.value.id)
    if (classIndex > -1) {
      classes.value[classIndex].studentCount--
      currentClass.value.studentCount--
    }
  }
}

const handleAssignStudents = () => {
  if (selectedStudents.value.length === 0) return
  
  // 检查班级容量
  const availableCapacity = currentClass.value.capacity - currentClass.value.studentCount
  if (selectedStudents.value.length > availableCapacity) {
    alert(`班级容量不足，最多只能分配 ${availableCapacity} 名学生`)
    return
  }
  
  // 分配学生到班级
  selectedStudents.value.forEach(studentId => {
    const studentIndex = students.value.findIndex(s => s.id === studentId)
    if (studentIndex > -1) {
      students.value[studentIndex].classId = currentClass.value.id
    }
  })
  
  // 更新班级学生人数
  const classIndex = classes.value.findIndex(c => c.id === currentClass.value.id)
  if (classIndex > -1) {
    classes.value[classIndex].studentCount += selectedStudents.value.length
    currentClass.value.studentCount += selectedStudents.value.length
    
    // 检查是否满员
    if (classes.value[classIndex].studentCount >= classes.value[classIndex].capacity) {
      classes.value[classIndex].status = '满员'
      currentClass.value.status = '满员'
    }
  }
  
  selectedStudents.value = []
  showAssignModal.value = false
}

const validateForm = () => {
  errors.value = {}
  
  if (!formData.value.code) {
    errors.value.code = '请输入班级代码'
  }
  
  if (!formData.value.name) {
    errors.value.name = '请输入班级名称'
  }
  
  if (!formData.value.major) {
    errors.value.major = '请选择所属专业'
  }
  
  return Object.keys(errors.value).length === 0
}

const handleSubmit = async () => {
  if (!validateForm()) return
  
  loading.value = true
  
  try {
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    if (showAddModal.value) {
      // 添加班级
      const newClass = {
        ...formData.value,
        id: Date.now(),
        studentCount: 0,
        createdAt: new Date().toLocaleString('zh-CN')
      }
      classes.value.unshift(newClass)
    } else {
      // 编辑班级
      const index = classes.value.findIndex(c => c.id === formData.value.id)
      if (index > -1) {
        classes.value[index] = { ...formData.value }
      }
    }
    
    closeModal()
  } catch (error) {
    console.error('操作失败:', error)
  } finally {
    loading.value = false
  }
}

const closeModal = () => {
  showAddModal.value = false
  showEditModal.value = false
  formData.value = {
    code: '',
    name: '',
    major: '',
    grade: '',
    teacher: '',
    teacherPhone: '',
    capacity: 30,
    status: '正常',
    description: ''
  }
  errors.value = {}
}

// 生命周期
onMounted(() => {
  // 设置页面标题
  document.title = '班级管理 - 新生报到服务平台'
})
</script>

<style scoped>
/* 自定义样式 */
.transition-colors {
  transition-property: color, background-color, border-color;
  transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
  transition-duration: 150ms;
}
</style>